package com.ruicar.afs.cloud.batch.monthend.process;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.batch.dayend.handle.run.SystemJdbcConfig;
import com.ruicar.afs.cloud.batch.frame.AbsBatchRunner;
import com.ruicar.afs.cloud.common.config.VoucherConstant;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.modules.contract.enums.VoucherStatusEnum;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;

/**
 * @author infinity
 * @version 1.0
 * @date 2020/8/18 11:48
 */
@Slf4j
public class VoucherMonthlySendFlowBathRunner extends AbsBatchRunner {
    private SystemJdbcConfig systemJdbcConfig= SpringContextHolder.getBean(SystemJdbcConfig.class);
    private UidGenerator uidGenerator= SpringContextHolder.getBean(UidGenerator.class);
    @Override
    public void process(String param) {
        //发送凭证信息
        log.info("月结凭证信息--开始");
        boolean isFinish = false;
        Connection contract = this.getConnection(systemJdbcConfig.getBasic());
        Connection contractAcount = this.getConnection(systemJdbcConfig.getAccount());
        while (!isFinish) {
            String loadBreakPoint = loadBreakPoint();
            logger.info("读取==={}", loadBreakPoint);
            isFinish = handleFlow(loadBreakPoint,contract,contractAcount);
        }
        log.info("发送凭证信息--结束");
    }

    private boolean handleFlow(String loadBreakPoint, Connection contract, Connection contractAcount) {
        Long id = null;
        PreparedStatement ps = null;
        PreparedStatement psflowCount = null;
        ResultSet rs = null;
        ResultSet rsflow = null;
        PreparedStatement psFlow = null;
        try {
            StringBuffer sqlFlow = new StringBuffer();
            sqlFlow.append("select id from  voucher_flow_info where trans_no=? ");
            psflowCount = contractAcount.prepareStatement(sqlFlow.toString());
            id = getId(loadBreakPoint, psflowCount, rsflow);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("startId", id);
            StringBuffer sql = new StringBuffer();
            sql.append("  select accounting.id,accounting.trans_id,accounting.fee_type,accounting.buried_point_no,accounting.contract_no,accounting.keep_account_date, ");
            sql.append("  info.business_type,info.channel_full_name from  basic_business_accounting  accounting  ");
            sql.append("  inner join basic_main_info info   on   info.contract_no = accounting.contract_no where accounting.send_status=?  ");
            if (id != null) {
                sql.append("  and  accounting.id>? order by accounting.id asc  limit 0, ?  ");
            } else {
                sql.append("  order by accounting.id asc  limit 0, ?   ");
            }
            //核算明细
            StringBuffer saveFlow = new StringBuffer();
            saveFlow.append("insert into voucher_flow_info(id,trans_no,buried_point_no,contract_no,status,dealer_name ,business_type,keep_account_date ) ");
            saveFlow.append("values(?,?,?,?,?,?,?,?)");
            ps = contract.prepareStatement(sql.toString());
            psFlow = contractAcount.prepareStatement(saveFlow.toString());
            ps.setString(1, "notSend");
            if (id != null) {
                ps.setLong(2, id);
                ps.setInt(3, VoucherConstant.batchesSize);
            } else {
                ps.setInt(2, VoucherConstant.batchesSize);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                rs.previous();
            } else {
                return Boolean.TRUE;
            }
            String transNo = null;

            while (rs.next()) {
                id = rs.getLong("id");
                transNo = rs.getString("trans_id");
                String buriedPointNo = rs.getString("buried_point_no");
                String contractNo = rs.getString("contract_no");
                String dealerName = rs.getString("channel_full_name");
                String businessype = rs.getString("business_type");
                Date keepaAccountDate = rs.getDate("keep_account_date");
                psFlow.setLong(1, uidGenerator.getUID());
                psFlow.setString(2, transNo);
                psFlow.setString(3, buriedPointNo);
                psFlow.setString(4, contractNo);
                psFlow.setString(5, AfsEnumUtil.key(VoucherStatusEnum.NOT_CREATED));
                psFlow.setString(6, dealerName);
                psFlow.setString(7, businessype);
                psFlow.setDate(8, keepaAccountDate);
                psFlow.addBatch();
            }
            psFlow.executeBatch();
            jsonObject.put("endId", id);
            jsonObject.put("targetId", transNo);
            saveBreakPoint(jsonObject.toString());
            contractAcount.commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AfsBaseException(e.getMessage());
        } finally {
            clean(ps);
            clean(rs);
            clean(psFlow);
        }
        return Boolean.FALSE;
    }

    //获取断点id
    private Long getId(String loadBreakPoint, PreparedStatement psflowCount, ResultSet rsflow) throws SQLException {
        if (StringUtil.isBlank(loadBreakPoint))
            return null;
        Long id = null;
        JSONObject jsonObject = JSONObject.parseObject(loadBreakPoint);
        Long startId = (Long) jsonObject.get("startId");
        Long endId = (Long) jsonObject.get("endId");
        String targetId = (String) jsonObject.get("targetId");
        if (targetId != null) {
            psflowCount.setString(1, targetId);
            rsflow = psflowCount.executeQuery();
            if (rsflow.next()) {
                id = endId;
            } else {
                id = startId;
            }
        }
        return id;
    }
}
